package com.mounting.wechat.modules.mp.service.imlp;

import com.alibaba.fastjson.JSONObject;
import com.mounting.wechat.common.api.ApiConstant;
import com.mounting.wechat.common.api.WechatConstant;
import com.mounting.wechat.common.http.HttpSender;
import com.mounting.wechat.common.util.SHA1;
import com.mounting.wechat.common.util.UrlBuilder;
import com.mounting.wechat.modules.mp.entity.WxMpMessage;
import com.mounting.wechat.modules.mp.entity.WxMpOutMessage;
import com.mounting.wechat.modules.mp.entity.WxMpOutTextMessage;
import com.mounting.wechat.modules.mp.service.WechatMpService;
import lombok.extern.apachecommons.CommonsLog;
import org.springframework.stereotype.Service;

/**
 * @author : lianghanmao
 * @date : 2022/11/17
 */
@Service
@CommonsLog
public class WechatMpServiceImpl implements WechatMpService {

    @Override
    public boolean verifySign(String signature, String timestamp, String nonce) {
        try {
            String token = "liangmaomao";
            return SHA1.gen(token, timestamp, nonce).equals(signature);
        } catch (Exception e) {
            log.error("Checking signature failed, and the reason is :" + e.getMessage());
            return false;
        }
    }

    @Override
    public boolean activelySendMessages(String appid, WxMpMessage wxMpMessage) {
        log.info("主动回复消息" + wxMpMessage);
        String url = UrlBuilder.fromBaseUrl(WechatConstant.MESSAGE_URL).queryParam("from_appid", appid).build();
        log.info("url:" + url);
        WxMpOutTextMessage textMessage = new WxMpOutTextMessage();
        textMessage.setContent("自动回复消息[" + wxMpMessage.getContent() + "]");
        textMessage.setFromUserName(wxMpMessage.getFromUserName());
        textMessage.setToUserName(wxMpMessage.getToUserName());
        textMessage.setCreateTime(System.currentTimeMillis());
        String outPutMessage = JSONObject.toJSONString(textMessage);
        log.info("post body:" + outPutMessage);
        String body = new HttpSender().post(url, outPutMessage).getBody();
        log.info("发送消息 [" +body+"] ");
        return false;
    }

    @Override
    public String passivelySendMessages(WxMpMessage wxMpMessage) {
        log.info("========= 被动回复消息 =========");
        WxMpOutTextMessage textMessage = new WxMpOutTextMessage();
        if (WechatConstant.MessageType.TEXT.equals(wxMpMessage.getMsgType())){
            // 教给机器人回复问题
            textMessage.setContent(this.answerTextOutMessage(wxMpMessage.getContent(),wxMpMessage.getFromUserName()));
        }else {
            textMessage.setContent("未适配["+wxMpMessage.getMsgType()+"]消息");
        }
        textMessage.setFromUserName(wxMpMessage.getToUserName());
        textMessage.setToUserName(wxMpMessage.getFromUserName());
        textMessage.setCreateTime(System.currentTimeMillis());

        return JSONObject.toJSONString(textMessage);
    }


    /**
     * 回答文本消息
     * @param question:问题
     * @param fromUser:提问人（用于关联上下文）
     * @return
     */
    private String answerTextOutMessage(String question,String fromUser){
        //由于机器人过于啥bear，需要一些人工的干预
        if (!question.contains("只因")){
            JSONObject response = JSONObject.parseObject(new HttpSender().get(buildUrlByQuestion(question, fromUser)).getBody());
            return response.getJSONObject("result").getString("reply");
        }
        return "小黑子露出鸡脚了吧";
    }


    /**
     *
     * @param question 问题
     * @param fromUser 提问人（用于关联上下文）
     * @return
     */
    private String buildUrlByQuestion(String question,String fromUser){
        return UrlBuilder.fromBaseUrl(ApiConstant.ROBOT_URL)
                .queryParam("key", ApiConstant.API_KEY)
                .queryParam("question", question)
                .queryParam("uniqueid",fromUser)
                .queryParam("priv","1")
                .build(true);
    }

}
